﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate.UserTypes;
using WebNext.Domain.Entities;
using NHibernate.SqlTypes;
using System.Data;
using System.Xml.Serialization;
using System.IO;
using NHibernate;
using Newtonsoft.Json;
using System.Data.SqlClient;

namespace WebNext.DataAccess.Mappings
{
	class EntryContentJsonSerializer : IUserType
	{
		private JsonSerializerSettings serializationSettings;

		public EntryContentJsonSerializer()
		{
			this.serializationSettings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Objects };
		}

		public object Assemble(object cached, object owner)
		{
			return cached;
		}

		public object DeepCopy(object value)
		{
			return value;
		}

		public object Disassemble(object value)
		{
			return value;
		}

		public bool Equals(object x, object y)
		{
			return object.Equals(x, y);
		}

		public int GetHashCode(object x)
		{
			return x.GetHashCode();
		}

		public bool IsMutable
		{
			get { return false; }
		}

		public object NullSafeGet(System.Data.IDataReader rs, string[] names, object owner)
		{
			string contentString = NHibernateUtil.AnsiString.NullSafeGet(rs, names[0]) as string;
			if (string.IsNullOrEmpty(contentString))
			{
				return null;
			}
			else
			{
				object result = JsonConvert.DeserializeObject<IList<EntryElement>>(contentString, this.serializationSettings);
				return result;
			}
		}

		public void NullSafeSet(System.Data.IDbCommand cmd, object value, int index)
		{
			IDataParameter parameter = (IDataParameter)cmd.Parameters[index];
			if (value ==null)
			{
				parameter.Value = DBNull.Value;
			}
			else
			{
				parameter.Value = JsonConvert.SerializeObject(value, this.serializationSettings);
				SqlParameter sqlParameter = parameter as SqlParameter;
				if (sqlParameter != null)
				{
					sqlParameter.Size = -1;
				}
			}
		}

		public object Replace(object original, object target, object owner)
		{
			return original;
		}

		public Type ReturnedType
		{
			get { return typeof(Entry); }
		}

		public NHibernate.SqlTypes.SqlType[] SqlTypes
		{
			get { return new SqlType[] { new StringSqlType() }; }
		}
	}
}
